package com.gu.service.impl;

import Utils.JwtUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.boot.exception.DiyException;
import com.gu.entity.TOrder;
import com.gu.entity.vo.OrderVo;
import com.gu.service.CourseClient;
import com.gu.service.TOrderService;
import com.gu.mapper.TOrderMapper;
import com.gu.service.UCenterClient;
import com.gu.untils.CreateOrderNo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 *
 */
@Service
public class TOrderServiceImpl extends ServiceImpl<TOrderMapper, TOrder>
    implements TOrderService{

    @Resource
    private CourseClient courseClient;

    @Resource
    private UCenterClient centerClient;

    @Override
    public OrderVo createOrderNo(String courseId, String  memberId) {

        Map<String, Object> courseMap = courseClient.getCourseForOrder(courseId);
        Map<String, Object> memberMap = centerClient.getUserInfo(memberId);

        String course_title = (String) courseMap.get("course_title");
        String course_cover = (String) courseMap.get("course_cover");
        String teacher_name = (String) courseMap.get("teacher_name");

        String mobile = (String) memberMap.get("mobile");
        String nickname = (String) memberMap.get("nickname");

        String orderNo = CreateOrderNo.create();

        TOrder order = new TOrder();
        order.setCourseId(courseId);
        order.setCourseCover(course_cover);
        order.setCourseTitle(course_title);
        order.setTeacherName(teacher_name);
        order.setCourseId(courseId);
        order.setMemberId(memberId);
        order.setMobile(mobile);
        order.setNickname(nickname);
        order.setOrderNo(orderNo);

        boolean result = this.save(order);
        if (!result){
            throw new DiyException("55555","创建订单失败！");
        }
        //再查一遍数据库，获取订单id
        QueryWrapper<TOrder> tOrderQueryWrapper = new QueryWrapper<>();
        tOrderQueryWrapper.eq("order_no",orderNo);
        TOrder tOrder = this.getOne(tOrderQueryWrapper);

        OrderVo orderVo = new OrderVo();
        BeanUtils.copyProperties(tOrder,orderVo);
        return orderVo;
    }
}




